<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{shared/header(Mytitle='问答')}"/>
<body class="min-h-screen bg-gray-100 font-sans">
<nav th:replace="~{shared/nav}"/>
<div class="flex h-screen">
    <!-- 侧边栏 -->
    <div class="w-1/6 bg-gray-200 p-4">
        <div class="mt-20">
            <h2 class="text-lg font-bold mb-2 py-2 ">会话记录</h2>
            <div id="EventListenerChatList">
                <div id="chatList" class="h-120 overflow-y-auto">
                    <div th:each="chat , iterStat : ${chatList}"
                         class="mb-4 hover:bg-green-400 flex items-center rounded-md py-2 px-4">
                        <button th:id="${chat.id}" onclick="(showEnsureModal(this))" th:value="${chat.ChatName}"
                                class="mr-2 flex items-center">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-red-500" viewBox="0 0 20 20"
                                 fill="currentColor">
                                <path d="M15 3a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h1V3a1 1 0 1 1 2 0v1h6V3a1 1 0 1 1 2 0v1h1zM8 7V14a1 1 0 0 0 2 0V7a1 1 0 0 0-2 0zm4 0V14a1 1 0 0 0 2 0V7a1 1 0 0 0-2 0z"/>
                            </svg>
                        </button>
                        <input type="radio" th:id="${'sessionRadio_' + chat.id}" name="sessionRadio"
                               class="mr-2 hidden custom-radio">
                        <!-- 添加垃圾桶图标按钮 -->
                        <label th:for="${'sessionRadio_' + chat.id}" class="cursor-pointer flex items-center w-full">
                            <!-- 垃圾桶按钮之后是 chatName 的 span -->
                            <span th:text="${chat.chatName}" class="flex-grow"></span>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500 hidden selected-icon"
                                 viewBox="0 0 20 20" fill="currentColor">
                                <path d="M9.293 15.293a1 1 0 0 1-1.414 0l-5-5a1 1 0 1 1 1.414-1.414L9 12.086l8.293-8.293a1 1 0 1 1 1.414 1.414l-9 9a1 1 0 0 1-1.414 0z"/>
                            </svg>
                        </label>
                    </div>
                </div>
                <div class="mb-4 hover:bg-green-400 flex items-center rounded-md py-2 px-4">
                    <input type="radio" th:id="1" name="nima" onclick="reloadChatList()"
                           class="mr-2 hidden custom-radio">
                    <label th:for="1" class="cursor-pointer flex items-center w-full">
                        <span th:text="新建会话" class="flex-grow"></span>
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-green-500 selected-icon"
                             viewBox="0 0 20 20" fill="currentColor">
                            <path d="M10 2.5a1 1 0 0 1 1 1v5h5a1 1 0 0 1 0 2h-5v5a1 1 0 0 1-2 0v-5H4a1 1 0 0 1 0-2h5v-5a1 1 0 0 1 1-1z"/>
                        </svg>
                    </label>
                </div>
            </div>
        </div>

    </div>
    <div id="total" class="flex-grow flex items-center justify-center mr-32">
        <!-- 主要内容区域 -->
        <div class="flex-1">
            <div class="max-w-2xl mx-auto p-4">
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <div class="mb-4">
                        <div class="font-bold text-lg text-blue-600 mb-2">大模型AI:</div>
                        <div id="chat-box" class="h-80 overflow-y-auto">

                        </div>
                    </div>
                    <div class="flex items-center">
                        <input id="usermessage" type="text" placeholder="请输入信息"
                               class="flex-1 border rounded p-2 mr-2"/>
                        <button onclick="sendMessage()" id="sendButton"
                                class="bg-blue-500 text-white px-4 py-2 rounded">发送
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="ensureModal" class="fixed inset-0 z-50 overflow-auto bg-gray-800 bg-opacity-50 hidden">
    <div class="flex items-center justify-center min-h-screen">
        <div class="bg-white rounded-lg p-8">
            <h2 id="modelTitle" class="text-xl font-bold mb-4">Modal Title</h2>
            <p id="modalContent" class="text-gray-700"></p>
            <button onclick="removeChat();closeMyModal()" id="removeChat"
                    class="mt-4 px-4 py-2 bg-red-400 text-white rounded hover:bg-red-500">确定
            </button>
            <button onclick="closeMyModal()" id="closeModal"
                    class="mt-4 px-4 py-2 bg-gray-400 text-white rounded hover:bg-gray-500">取消
            </button>
        </div>
    </div>
</div>
<footer th:replace="~{shared/footer}"/>
<input type="hidden" id="getAiMessagesUrl" th:value="@{/model/getmessage}"/>
<input type="hidden" id="createNewChatUrl" th:value="@{/model/createChat}"/>
<input type="hidden" id="reloadMessagesUrl" th:value="@{/model/reloadMessages}"/>
<input type="hidden" id="deleteChatUrl" th:value="@{/model/deleteChat}"/>
<input type="hidden" id="updateChatLastMessagesUrl" th:value="@{/model/updateChatLastMessages}"/>

</body>
</html>
<script th:inline="javascript">
    let bro = 0;
    let nowChatId = -1
    let lastMessageId = -1
    let changedMessageId = -1
    let chatList = [[${chatList}]];
    let deleteChatId = -1
    document.addEventListener('DOMContentLoaded', async function () {
        const chatContainer = $('#EventListenerChatList');
        chatContainer.click(async function (event) {
            var label = event.target.closest('[for^="sessionRadio_"]');
            if (label) {
                var chatId = label.getAttribute('for').replace('sessionRadio_', '');
                var radioId = 'sessionRadio_' + chatId;
                toggleRadio(event, radioId);
                await reloadMessagesList(chatId, -1);
            }
        });
        // const chatButtons = $('[id^="index_"]');
        // chatButtons.each(function() {
        //     $(this).click(async function (event) {
        //         const index = $(this).attr('id').replace('index_', '');
        //         showEnsureModal(index);
        //     });
        // });
    });

    function showEnsureModal(target) {
        var index = target.getAttribute('value')
        deleteChatId = target.getAttribute('id')
        console.log("deleteChatId:" + deleteChatId)
        $('#modalContent').text(index);
        $('#modelTitle').text('是否要删除该会话？')
        $('#ensureModal').removeClass('hidden');
    }

    async function removeChat() {
        console.log("removeChat.yes!!!!!!!")
        try {
            const response = await $.ajax({
                type: "POST",
                url: $('#deleteChatUrl').val(),
                data: {
                    chatId: deleteChatId
                },
            });

            const chatBox = $("#chat-box");
            console.log("removeChatSuccess")
            nowChatId = -1
            lastMessageId = -1
            deleteChatId = -1
            await loadChatList();
            chatBox.empty();
        } catch (error) {
            console.error("Error fetching data: " + error);
        }
    }

    async function newChat() {
        lastMessageId = -1
        // 新建聊天，建个ajax把userId传过去先
        try {
            const response = await $.ajax({
                type: 'GET',
                url: $('#createNewChatUrl').val(),
                data: {
                    userId: [[${user.id}]],
                },
            });

            console.log("来自newChat的nowChatId" + response.message[0]);
            console.log("以及root的id" + response.message[1]);
            nowChatId = response.message[0];
            lastMessageId = response.message[1];
            let thisChatId = nowChatId;
            thisChatId = 'sessionRadio_' + thisChatId
            await loadChatList();
            await toggleRadio(event, thisChatId)
        } catch (error) {
            console.error("Error during newChat:", error);
        }
    }

    function closeMyModal() {
        $('#ensureModal').addClass('hidden')
    }

    async function reloadMessagesList(ChatId, index) {
        try {
            const response = await new Promise((resolve, reject) => {
                $.ajax({
                    type: "GET",
                    url: $('#reloadMessagesUrl').val(),
                    data: {
                        chatId: ChatId,
                        indexId: index,
                    },
                    success: resolve,
                    error: reject,
                });
            });


            messagesList = response.message;
            lastMessageId = messagesList[messagesList.length - 1].id;
            loadMessagesList(messagesList);
            console.log(response.message);

        } catch (error) {
            console.error("Error fetching data: " + error);
        }
    }

    async function updateChatLastMessages(nowChatId, nowPage, broPage) {
        try {
            const response = await $.ajax({
                type: "POST",
                url: $('#updateChatLastMessagesUrl').val(),
                data: {
                    chatId: nowChatId,
                    preId: nowPage,
                    nextId: broPage,
                    lastMessageId: lastMessageId,
                },
            });

            // 成功获取数据后，更新页面
            console.log("nowChatId is" + nowChatId);

        } catch (error) {
            console.error("Error fetching data: " + error);
        }
    }


    function toggleRadio(event, radioId) {
        var radios = document.getElementsByName('sessionRadio');
        radios.forEach(function (radio) {
            var icon = radio.nextElementSibling.querySelector('.selected-icon');
            icon.classList.add('hidden');

            var div = radio.closest('.mb-4');
            div.classList.remove('bg-gray-400');
        });
        var selectedIcon = document.getElementById(radioId).nextElementSibling.querySelector('.selected-icon');
        selectedIcon.classList.remove('hidden');
        var selectedDiv = document.getElementById(radioId).closest('.mb-4');
        selectedDiv.classList.add('bg-gray-400');

        nowChatId = radioId.replace(/^sessionRadio_/, '');
    }

    async function sendMessage() {
        const userInput = document.getElementById('usermessage');
        var sendButton = document.getElementById("sendButton");
        const chatBox = document.getElementById('chat-box');
        let userContent = "";
        if (bro === 0) {
            console.log("孩子send");
            userContent = $('#usermessage').val().trim();
        } else {
            console.log("兄弟send");
            userContent = $('#bromessage').val().trim();
        }
        const userchat = $('#usermessage').val().trim();

        userInput.disabled = true;
        // 禁用按钮并更改样式
        sendButton.disabled = true;
        sendButton.classList.remove("bg-blue-500");
        sendButton.classList.add("bg-gray-500", "cursor-not-allowed");

        console.log("sendMessage的data：" + nowChatId)
        if (nowChatId === -1) {
            await newChat()
            console.log("newChat成功")
        }
        try {
            const response = await new Promise((resolve, reject) => {
                $.ajax({
                    type: 'GET',
                    url: $('#getAiMessagesUrl').val(),
                    data: {
                        bro: bro,
                        userContent: userContent,
                        chatId: nowChatId,
                        lastMessageId: lastMessageId,
                        changedMessageId: changedMessageId,
                    },
                    success: resolve,
                    error: reject
                });
            });
            // 启用输入框
            userInput.disabled = false;
            userInput.value = "";
            // 启用按钮并恢复样式
            sendButton.disabled = false;
            sendButton.classList.remove("bg-gray-500", "cursor-not-allowed");
            sendButton.classList.add("bg-blue-500");

            await reloadMessagesList(nowChatId, -1);
        } catch (error) {
            console.error(error);
        }
    }


    function reloadChatList() {
        const chatBox = $("#chat-box");
        chatList = [[${chatList}]];
        // 去掉选中样式
        var radios = document.getElementsByName('sessionRadio');
        radios.forEach(function (radio) {
            var icon = radio.nextElementSibling.querySelector('.selected-icon');
            icon.classList.add('hidden');

            var div = radio.closest('.mb-4');
            div.classList.remove('bg-gray-400');
        });
        chatBox.empty();
        nowChatId = -1;
    }

    function loadChatList() {
        console.log("loadChatList!!!")
        return new Promise(resolve => {
            $("#chatList").load(window.location.href + " #chatList", function () {
                resolve();
            });
        });
    }

    function loadMessagesList(messagesList) {
        const chatBox = $("#chat-box");
        // 清空现有内容
        chatBox.empty();
        // 遍历数组，生成 HTML 元素并添加到容器中
        messagesList.forEach(function (item) {
            // 用户消息
            const userItem = $("<div>").addClass("mb-2 flex items-start"); // 使用相对定位
            const integerArray = item.broIdList.split("-").map(function (numberString) {
                return parseInt(numberString, 10);
            });
            let nowPage;
            for (var i = 0; i < integerArray.length; i++) {
                if (integerArray[i] === item.id) {
                    nowPage = i + 1
                }
            }

            // 添加铅笔图标按钮
            const editButton = $("<button>").addClass("left-4").html('&#9998;').click(function () {
                const parentDiv = $(this).closest("div");
                parentDiv.find("strong, span").remove();

                // 隐藏铅笔图标按钮
                editButton.hide();
                parentDiv.find("#paging").remove();
                // 创建输入框
                const inputField = $("<textarea>").val(item.userContent).attr("id", "bromessage");

                // 创建提交按钮
                const submitButton = $("<button>")
                    .attr("id", "brobutton")
                    .addClass("bg-green-500 text-white font-bold py-1 px-2 rounded mr-2")
                    .text("提交")
                    .click(async function () {
                        const broMessage = document.getElementById('bromessage');
                        var broButton = document.getElementById("brobutton");
                        changedMessageId = item.id;
                        console.log(changedMessageId);
                        bro = 1;
                        broMessage.disabled = true;
                        broButton.disabled = true;
                        await sendMessage();
                        broMessage.disabled = false;
                        broButton.disabled = false;
                        bro = 0;
                        console.log("bro is" + bro)
                        // 获取输入框的值，更新userText，并显示铅笔图标按钮
                        const updatedContent = inputField.val();
                        const userText = $("<span>").text(updatedContent);
                        // editButton.show();
                        userItem.append(userText);
                        // 移除输入框和按钮
                        inputField.remove();
                        submitButton.remove();
                        cancelButton.remove();
                    });

                // 创建取消按钮
                const cancelButton = $("<button>")
                    .addClass("bg-gray-500 text-white font-bold py-1 px-2 rounded")
                    .text("取消")
                    .click(function () {
                        // 显示铅笔图标按钮，移除输入框和按钮
                        const userText = $("<span>").text(item.userContent);
                        editButton.show();
                        userItem.append(userText).append(createPaginationDiv(nowPage, integerArray.length, item.broIdList));


                        inputField.remove();
                        submitButton.remove();
                        cancelButton.remove();
                    });

                // 将生成的输入框和按钮追加到userItem中
                userItem.append($("<strong>").text("你:")).append(inputField).append(submitButton).append(cancelButton);
            });
            const editButtonDiv = $("<div>").addClass("mb-2").text(" ").append(editButton);
            const userText = $("<span>").text(item.userContent);
            userItem.append(editButton).append($("<strong>").text("你:")).append(userText).append(createPaginationDiv(nowPage, integerArray.length, item.broIdList));

            // 大模型AI消息
            const modelItem = $("<div>").addClass("mb-2");
            const modelText = $("<span>").text(item.modelContent);
            modelItem.append($("<strong>").text("大模型AI:")).append(modelText);

            // 将生成的用户消息和大模型AI消息追加到chatBox中
            chatBox.append(userItem).append(modelItem);
        });
    }

    function createPaginationDiv(nowPage, totalPage, broIdList) {
        let integerArray = broIdList.split("-").map(function (numberString) {
            return parseInt(numberString, 10);
        });

        const paginationDiv = $("<div>").addClass("flex items-center ml-auto").attr("id", "paging");

        const prevButton = $("<button>").addClass("mr-2").html('&lt;').click(async function () {
            let Array = integerArray
            if (nowPage !== 1) {
                await updateChatLastMessages(nowChatId, Array[nowPage - 1], Array[nowPage - 1 - 1])
                console.log("Array" + Array[nowPage - 1 - 1]);
                await reloadMessagesList(nowChatId, Array[nowPage - 1 - 1]);
            }
        });
        const pageNumber = $("<span>").addClass("mx-2").text(nowPage + '/' + totalPage);
        const nextButton = $("<button>").addClass("ml-2").html('&gt;').click(async function () {
            let Array = integerArray
            if (nowPage !== totalPage) {
                await updateChatLastMessages(nowChatId, Array[nowPage - 1], Array[nowPage])
                console.log("Array" + Array[nowPage]);
                await reloadMessagesList(nowChatId, Array[nowPage]);
            }
        });

        paginationDiv.append(prevButton).append(pageNumber).append(nextButton);

        return paginationDiv;
    }
</script>